<template>
  <div class="m-4 mr-0 overflow-hidden bg-white">
    <div style="border: 1px solid #d8d8d8; padding: 2px; margin: 4px">
      <span style="color: rgb(174, 172, 172)">
        注意：点击部门名称显示本部门中的人员（不包含下级部门中的人员），再次点击部门可显示所有人员。
      </span>
    </div>
    <BasicTree
      v-if="treeData.length"
      title="部门列表"
      toolbar
      search
      treeWrapperClassName="h-[calc(100%-35px)] overflow-auto"
      :clickRowToExpand="false"
      :treeData="treeData"
      :fieldNames="{ key: 'key', title: 'title' }"
      @select="handleSelect"
      :defaultExpandAll="false"
      :defaultExpandLevel="1"
    />
  </div>
</template>
<script lang="ts">
  import { defineComponent, onMounted, ref } from 'vue';

  import { BasicTree, TreeItem } from '/@/components/Tree';
  import { getUserDeptsTree } from '/@/api/project/dept';

  import { useUserStore } from '/@/store/modules/user';

  export default defineComponent({
    name: 'DeptTree',
    components: { BasicTree },

    emits: ['select'],
    setup(_, { emit }) {
      const treeData = ref<TreeItem[]>([]);

      //获取当前登录用户项目编码
      const userStore = useUserStore();
      const currentProjectCode = userStore.getUserCurrentProjectCode;

      async function getDeptList() {
        getUserDeptsTree({ pcode: currentProjectCode })
          .then((res) => {
            console.log('res', res);
            //res判断结果：同时==undefined和null
            treeData.value = res as unknown as TreeItem[];
          })
          .catch((ex) => {
            console.log('catch ', ex);
            // createMessage.error(ex.msg);
          });
      }

      function handleSelect(keys) {
        emit('select', keys[0]);
      }

      onMounted(() => {
        getDeptList();
      });
      return { treeData, handleSelect, getDeptList };
    },
  });
</script>
